package com.project.common;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.thymeleaf.Arguments;
import org.thymeleaf.dom.Element;
import org.thymeleaf.dom.Node;
import org.thymeleaf.dom.Text;
import org.thymeleaf.processor.element.AbstractMarkupSubstitutionElementProcessor;
import org.thymeleaf.spring4.context.SpringWebContext;

import com.google.common.collect.Lists;
import com.project.service.sys.AreaService;

@Component
public class AreaElementProcessor extends AbstractMarkupSubstitutionElementProcessor{

	public AreaElementProcessor() {
		super("write");
	}

	@Override
	protected List<Node> getMarkupSubstitutes(Arguments paramArguments, Element paramElement) {
		ApplicationContext appCtx = ((SpringWebContext)paramArguments.getContext()).getApplicationContext();
		AreaService areaService =appCtx.getBean(AreaService.class);
		String province = paramElement.getAttributeValue("province");
		String city = paramElement.getAttributeValue("city");
		String district = paramElement.getAttributeValue("district");
		StringBuffer area = new StringBuffer();
		if(StringUtils.isNotBlank(province))
			area.append(areaService.getAreaNameByCode(province));
		if(StringUtils.isNotBlank(city))
			area.append(areaService.getAreaNameByCode(city));
		if(StringUtils.isNotBlank(district))
			area.append(areaService.getAreaNameByCode(district));
		Element container = new Element("span");
		Text text = new Text(area.toString());
		container.addChild(text);
		List<Node> nodes = Lists.newArrayList();
		nodes.add(container);
		return nodes;
	}

	@Override
	public int getPrecedence() {
		// TODO Auto-generated method stub
		return 0;
	}

}
